/*
 * @Author: ZhaoDong
 * @Date: 2022-07-07 00:24:07
 * @LastEditors: ZhaoDong
 * @LastEditTime: 2022-07-28 17:43:57
 * @Description: axios
 */
import { get } from 'lodash-es';
import axios, { AxiosInstance, AxiosRequestConfig } from 'axios';
import { useUserStoreHook } from '/@/store/modules/user';
import { addRequest, removeRequest } from './axiosCancelRequest';

import { ElMessage } from 'element-plus';
import 'element-plus/theme-chalk/src/message.scss';
import { getToken } from '/@/utils/cookies';

const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
console.log('BASE_URL', BASE_URL);

const SUCCESS_CODE = '000000';

function createService(): AxiosInstance {
  const service = axios.create();
  // service.defaults.baseURL = BASE_URL;
  // service.defaults.withCredentials = false;
  // service.defaults.timeout = 20000;

  // Request interceptors
  service.interceptors.request.use(
    config => {
      removeRequest(config);
      addRequest(config);
      return config;
    },
    error => Promise.reject(error)
  );

  // Response interceptors
  service.interceptors.response.use(
    response => {
      removeRequest(response.config);
      const resData = response.data as any;
      const code = resData.code;
      if (code === undefined) {
        return Promise.reject(new Error('接口返回数据格式错误'));
      } else {
        switch (code) {
          case SUCCESS_CODE:
            return resData;
          default:
            ElMessage.error(resData.message || 'Error');
            return Promise.reject(new Error('Response Error'));
        }
      }
    },
    error => {
      const status = get(error, 'response.status');
      switch (status) {
        case 400:
          error.message = '请求错误！';
          break;
        case 401:
          error.message = '未授权，请登录！';
          break;
        case 403:
          // token 过期，退出&刷新页面
          useUserStoreHook().logout();
          // location.reload();
          window.location.href = import.meta.env.VITE_APP_REDIRECT_AUTH;
          break;
        case 404:
          error.message = '请求地址出错';
          break;
        case 500:
          error.message = '服务器内部错误';
          break;
        case 501:
          error.message = '服务未实现';
          break;
        case 502:
          error.message = '网关错误';
          break;
        case 503:
          error.message = '服务不可用';
          break;
        case 504:
          error.message = '网关超时';
          break;
        default:
          error.message = '未知错误';
          break;
      }
      let _error_message = error.message;
      if (error.response.data.message) {
        _error_message = error.response.data.message;
      }
      // cancelRequest 取消请求后会抛出 catch 错误， axios.isCancel 判断不是手动取消的错误则调用 errTip 提示
      // !axios.isCancel(error) && ElMessage.error(error.message);
      !axios.isCancel(error) && ElMessage.error(_error_message);
      return Promise.reject(error);
    }
  );
  return service;
}

/** 创建请求方法 */
function createRequestFunction(service: AxiosInstance) {
  return function (config: AxiosRequestConfig) {
    const configDefault = {
      headers: {
        // header 携带 Token
        Token: getToken() || null,
        'Content-Type': get(config, 'headers.Content-Type', 'application/json')
      },
      timeout: 20000,
      baseURL: BASE_URL,
      data: {}
    };
    return service(Object.assign(configDefault, config));
  };
}

export const service = createService();

export const request = createRequestFunction(service);

export default service;
